<?php

namespace app\listing\logic;
use app\data\util\HttpUtil;
use think\facade\Db;

class ShopifyListingLogic extends BasicLogic
{

    /**
     * @desc    刊登店铺数据接口
     * @author  luckyXiong
     * @date    2024-12-01
     */
    public function send_product_consumer($params)
    {
        htmlLog(['param' => $params], OPERATE_LOG . date('Ym') . '/send_product/' . date('Ymd') . '.txt');
        $shop_id = $params['shop_id'];
        $send_data = $params['send_data'];
        $product_id = $params['product_id'];
        $shop_info = Db::name('shops')->where('id', $shop_id)->find();
        $token = $shop_info['app_secret'];
        $version = Config('Logisticskey.shopify.api_versoin');
        if (empty($product_id)) {
            $operation = Config('Logisticskey.shopify.operation');
            $fulfill_url = $shop_info['myshopify_domain'] . $version . $operation;
            self::publish_product($fulfill_url, $send_data, $token, $params['listing_shop_product_id']);
        } else { //修改更新
            $fulfill_url = $shop_info['myshopify_domain'] . $version . '/products/' . $product_id . '.json';
            self::update_product($fulfill_url, $send_data, $token, $params['listing_shop_product_id']);
        }
        return true;
    }


    /**
     * @desc    刊登数据
     * @author  luckyXiong
     * @date    2024-12-01
     */
    private function publish_product($fulfill_url, $send_data, $token, $listing_shop_product_id)
    {
        $return = HttpUtil::postUrlShopify($fulfill_url, $send_data, $token);
        htmlLog(['response' => $return], OPERATE_LOG . date('Ym') . '/publish_product/' . date('Ymd') . '.txt');
        if (isset($return['product']['id']) && $return['product']['id']) {
            Db::name('listing_shop_product')->where(['id' => $listing_shop_product_id])->update(
                [
                    'product_shopify_id' => $return['product']['id'],
                    'listing_status' => 2,
                    'listing_time' => date("Y-m-d H:i:s", time()),
                    'publish_response' => json_encode($return),
                ]
            );
        } else {
            Db::name('listing_shop_product')->where(['id' => $listing_shop_product_id])->update(
                [
                    'product_shopify_id' => $return['product']['id'],
                    'listing_status' => 5,
                    'listing_time' => date("Y-m-d H:i:s", time()),
                    'publish_response' => json_encode($return),
                ]
            );
        }
        return true;
    }


    /**
     * @desc    修改发布数据
     * @author  luckyXiong
     * @date    2024-12-01
     */
    private function update_product($fulfill_url, $send_data, $token, $listing_shop_product_id)
    {
        htmlLog(['send_data' => $send_data], OPERATE_LOG . date('Ym') . '/update_product/' . date('Ymd') . '.txt');
        $return = HttpUtil::putUrlShopify($fulfill_url, $send_data, $token);
        if (isset($return['product']['id']) && $return['product']['id']) {
            Db::name('listing_shop_product')->where(['id' => $listing_shop_product_id])->update(
                [
                    'listing_status' => 2,
                    'update_time' => date("Y-m-d H:i:s", time()),
                    'publish_response' => json_encode($return),
                ]
            );
        }
        htmlLog(['response' => $return], OPERATE_LOG . date('Ym') . '/update_product/' . date('Ymd') . '.txt');
        return true;
    }

    //历史产品数据同步到仓库产品管理
    public function get_product_consumer($info)
    {

        $product_id  = $info['product_id'] ?? '';
        $shop_id     = $info['shop_id'] ?? '';
        $shop_info   = Db::name('shops')->where('id', $shop_id)->find();
        $version     = Config('Logisticskey.shopify.api_versoin');
        $fulfill_url = $shop_info['myshopify_domain'] . $version . '/products/' . $product_id . '.json';
        $token         = $shop_info['app_secret'];
        $product_info  = HttpUtil::getUrlShopify($fulfill_url, $token);
        if(!isset($product_info['product']))  return  true;
        $data =$product_info['product'];
        $product_variant_type = count($data['variants']) > 1 ? 2 : 1;
        $variants1 = current($data['variants']);
        $spu_info  = explode('-', $variants1['sku']);
        $spu       = $spu_info[0]??'';
        $product_images = $variants_json = $image_info = [];
        $product_types      = $data['product_type']??'';
        $product_type      = self::get_product_type($product_types);
        $listing_status    = self::get_listing_status($data['status']);
        $inventory_management = $variants1['inventory_management']??null;
        $inventory_policy     = $variants1['inventory_policy']??null;
        $inventory_support   = self::get_inventory_support($inventory_management,$inventory_policy);
        //数据写入在线店铺表中; qu_listing_shop_product
        $exist_shop_product = Db::name('listing_shop_product')->where(['product_shopify_id' => $data['id']])->find();
        if ($spu){
            if($data['images']){
                  foreach($data['images'] as $k=>$v){
                      $product_images[$k]['position'] = $v['position']??'';
                      $product_images[$k]['width']  = $v['width']??'';
                      $product_images[$k]['height'] = $v['height']??'';
                      if(isset($v['src']) && $v['src']){
                          $product_images[$k]['src'] = str_replace(" ", "", $v['src']);
                      }
                  }
                $image_info  = array_column($data['images'],'src','id');
            }

            if($data['variants']){
                $variants_json = $data['variants'];
                foreach($variants_json as $k=>$v){
                    $variants_json[$k]['inventory_support'] = $inventory_support;
                }
            }


            //图片集合;
            $iamges = array_column($product_images,'src');
            $product_insert = [
                    'shop_id'             => $shop_id,
                    'spu'                 => $spu,
                    'product_variant_type'=> $product_variant_type,
                    'product_shopify_id'  => $data['id'],
                    'product_tags'        => $data['tags'],
                    'product_title'       => $data['title'],
                    'product_desc'        => $data['body_html']??'',
                    'product_type'        => $product_type ?: '',
                    'supply_shop_name'    => $data['vendor'],
                    'product_images'      => $product_images   ? json_encode($product_images):'',
                    'options'             => $data['options']  ? json_encode($data['options']):'',
                    'variant_json'        => $variants_json    ? json_encode($variants_json):'',
                    'listing_status'      => $listing_status,
                    'seo_title'           => $data['handle'],
                    'update_time'         => get_real_time($data['updated_at']),
                    'create_time'         => get_real_time($data['created_at']),
                    'listing_time'        => get_real_time($data['published_at']),
                ];

                //仓库产品
                $inventory_product = [
                    'spu'                      => $spu,
                    'product_images'           => $iamges   ? json_encode([$iamges[0]]) :'',
                    'max_weight'               => $variants1['weight']??'',
                    'update_time'              => get_real_time($data['updated_at']),
                    'created_time'             => get_real_time($data['created_at']),
                    'published_time'           => get_real_time($data['published_at']),
                ];
                //seller_sku 多变体数据;
                $seller_sku_product  = self::varient_seller_sku($data['variants'],$spu,$variants1['weight'],$image_info);
                if(!$exist_shop_product){
                    Db::name('listing_shop_product')->insert($product_insert);
                }
                //todo 同时将产品信息写入线下产品表; product_seller_sku表
                self::add_inventory_spu($inventory_product,$seller_sku_product,$product_variant_type);
         }
        return   true;

    }




    /**
     * @desc    新增产品webhook回调数据
     * @author  luckyXiong
     * @date    2025-01-02
     */
    public function webhook_product_add($info)
    {

        htmlLog(['params'=>$info],OPERATE_LOG . date('Ym') . '/webhook_product_add/' . date('Ymd') . '.txt');
        $shop_id              = $info['shop_id'] ?? '';
        $data                 = $info;
        $product_variant_type = count($data['variants']) > 1 ? 2 : 1;
        $variants1            = current($data['variants']);
        $spu_info             = explode('-', $variants1['sku']);
        $spu                  = $spu_info[0]??'';
        $product_images       = $variants_json = $image_info = [];
        $product_type      = self::get_product_type($data['product_type']);
        $listing_status    = self::get_listing_status($data['status']);
        $inventory_management = $variants1['inventory_management']??null;
        $inventory_policy     = $variants1['inventory_policy']??null;
        $inventory_support   = self::get_inventory_support($inventory_management,$inventory_policy);
        //数据写入在线店铺表中; qu_listing_shop_product
        $exist_shop_product = Db::name('listing_shop_product')->where(['product_shopify_id' => $data['id']])->find();
        if ($spu){
            if($data['images']){
                foreach($data['images'] as $k=>$v){
                    $product_images[$k]['position'] = $v['position']??'';
                    $product_images[$k]['width']  = $v['width']??'';
                    $product_images[$k]['height'] = $v['height']??'';
                    if(isset($v['src']) && $v['src']){
                        $product_images[$k]['src'] = str_replace(" ", "", $v['src']);
                    }
                }
                $image_info  = array_column($data['images'],'src','id');
            }

            if($data['variants']){
                $variants_json = $data['variants'];
                foreach($variants_json as $k=>$v){
                    $variants_json[$k]['inventory_support'] = $inventory_support;
                }
            }
            //图片集合;
            $iamges = array_column($product_images,'src');

            $product_insert = [
                'shop_id'             => $shop_id,
                'spu'                 => $spu,
                'product_variant_type'=> $product_variant_type,
                'product_shopify_id'  => $data['id'],
                'product_tags'        => $data['tags'],
                'product_title'       => $data['title'],
                'product_desc'        => $data['body_html'],
                'product_type'        => $product_type ?: '',
                'supply_shop_name'    => $data['vendor'],
                'product_images'      => $product_images   ? json_encode($product_images):'',
                'options'             => $data['options']  ? json_encode($data['options']):'',
                'variant_json'        => $variants_json    ? json_encode($variants_json):'',
                'listing_status'      => $listing_status,
                'seo_title'           => $data['handle'],
                'update_time'         => get_real_time($data['updated_at']),
                'create_time'         => get_real_time($data['created_at']),
                'listing_time'        => get_real_time($data['published_at']),
            ];

            //仓库产品
            $inventory_product = [
                'spu'                      => $spu,
                'product_images'           => $iamges   ? json_encode([$iamges[0]]) :'',
                'max_weight'               => $variants1['weight']??'',
                'update_time'              => get_real_time($data['updated_at']),
                'created_time'             => get_real_time($data['created_at']),
                'published_time'           => get_real_time($data['published_at']),
            ];

            //seller_sku 多变体数据;
            $seller_sku_product  = self::varient_seller_sku($data['variants'],$spu,$inventory_product['max_weight'],$image_info);
            if(empty($exist_shop_product)){
                Db::name('listing_shop_product')->insert($product_insert);
            }

            //todo 同时将产品信息写入线下产品表; product_seller_sku表
            self::add_inventory_spu($inventory_product,$seller_sku_product,$product_variant_type);
        }
        return $this->jsonMessage(200, true, '操作成功', null);
    }


    /**
     * @desc    编辑产品webhook回调数据
     * @author  luckyXiong
     * @date    2025-01-02
     */
    public function webhook_product_edit($info)
    {
        htmlLog(['params'=>$info],OPERATE_LOG . date('Ym') . '/webhook_product_edit/' . date('Ymd') . '.txt');
        $shop_id     = $info['shop_id'] ?? '';
        $data        = $info;
        $product_variant_type = count($data['variants']) > 1 ? 2 : 1;
        $variants1 = current($data['variants']);
        $spu_info  = explode('-', $variants1['sku']);
        $spu       = $spu_info[0]??'';
        $product_images = $variants_json = $image_info = [];
        $product_types      = $data['product_type']??'';
        $product_type      = self::get_product_type($product_types);
        $listing_status    = self::get_listing_status($data['status']);
        $inventory_management = $variants1['inventory_management']??null;
        $inventory_policy     = $variants1['inventory_policy']??null;
        $inventory_support   = self::get_inventory_support($inventory_management,$inventory_policy);
        //数据写入在线店铺表中; qu_listing_shop_product
        $exist_shop_product = Db::name('listing_shop_product')->where(['product_shopify_id' => $data['id']])->find();
        if ($spu){
            if($data['images']){
                foreach($data['images'] as $k=>$v){
                    $product_images[$k]['position'] = $v['position']??'';
                    $product_images[$k]['width']  = $v['width']??'';
                    $product_images[$k]['height'] = $v['height']??'';
                    if(isset($v['src']) && $v['src']){
                        $product_images[$k]['src'] = str_replace(" ", "", $v['src']);
                    }
                }
                $image_info  = array_column($data['images'],'src','id');
            }

            if($data['variants']){
                $variants_json = $data['variants'];
                foreach($variants_json as $k=>$v){
                    $variants_json[$k]['inventory_support'] = $inventory_support;
                }
            }

            //图片集合;
            $iamges = array_column($product_images,'src');
            $product_insert = [
                'shop_id'             => $shop_id,
                'spu'                 => $spu,
                'product_variant_type'=> $product_variant_type,
                'product_shopify_id'  => $data['id'],
                'product_tags'        => $data['tags'],
                'product_title'       => $data['title'],
                'product_desc'        => $data['body_html'],
                'product_type'        => $product_type ?: '',
                'supply_shop_name'    => $data['vendor'],
                'product_images'      => $product_images   ? json_encode($product_images):'',
                'options'             => $data['options']  ? json_encode($data['options']):'',
                'variant_json'        => $variants_json    ? json_encode($variants_json):'',
                'listing_status'      => $listing_status,
                'seo_title'           => $data['handle'],
                'update_time'         => get_real_time($data['updated_at']),
                'create_time'         => get_real_time($data['created_at']),
                'listing_time'        => get_real_time($data['published_at']),
            ];


            $product_update = [
                'product_shopify_id'  => $data['id'],
                'product_tags'        => $data['tags'],
                'product_title'       => $data['title'],
                'product_desc'        => $data['body_html'],
                'product_type'        => $product_type ?: '',
                'supply_shop_name'    => $data['vendor'],
                'product_images'      => $product_images   ? json_encode($product_images):'',
                'options'             => $data['options']  ? json_encode($data['options']):'',
                'variant_json'        => $variants_json    ? json_encode($variants_json):'',
                'listing_status'      => $listing_status,
                'seo_title'           => $data['handle'],
                'update_time'         => get_real_time($data['updated_at']),
            ];

            //仓库产品
            $inventory_product = [
                'spu'                      => $spu,
                'product_images'           => $iamges   ? json_encode([$iamges[0]]) :'',
                'max_weight'               => $variants1['weight']??'',
                'update_time'              => get_real_time($data['updated_at']),
                'created_time'             => get_real_time($data['created_at']),
                'published_time'           => get_real_time($data['published_at']),
            ];
            //seller_sku 多变体数据;
            $seller_sku_product  = self::varient_seller_sku($data['variants'],$spu,$inventory_product['max_weight'],$image_info);
            if(empty($exist_shop_product)){
                Db::name('listing_shop_product')->insert($product_insert);
            }else{
                Db::name('listing_shop_product')->where(['product_shopify_id' => $data['id']])->update($product_update);
            }
            //todo 同时将产品信息写入线下产品表; product_seller_sku表
            self::add_inventory_spu($inventory_product,$seller_sku_product,$product_variant_type);
        }
        return $this->jsonMessage(200, true, '操作成功', null);
    }




    /**
     * @desc    获取产品类型
     * @author  luckyXiong
     * @date    2024-12-06
     */
    private function get_product_type($product_type)
    {
        if (!$product_type) return '';
        $where = [];
        $where[] = ['parent_id', '=', 0];
        $where[] = ['type_name', 'like', '%' . $product_type . '%'];
        $type_id = Db::name('product_attr_level')->where($where)->value('type_id');
        return $type_id;
    }

    /**
     * @desc    多变体数据
     * @author  luckyXiong
     * @date    2024-12-06
     */
    private function varient_seller_sku($variant_json, $spu, $weight, $image_info) {
        if (empty($variant_json)) {
            return [];
        }
        $uniqueSkus = [];

        // 处理变体数据并收集唯一的 SKU
        foreach ($variant_json as $variant) {
            $skuRaw = $variant['sku'] ?? '';
            if ($skuRaw === '') {
                continue;
            }

            $processedSku = get_product_sku($skuRaw, 1);
            $imageId = $variant['image_id'] ?? null;

            foreach (array_map('trim', explode(',', $processedSku)) as $sku) {
                if ($sku !== '' && !isset($uniqueSkus[$sku])) {
                    $uniqueSkus[$sku] = $imageId;
                }
            }
        }

        // 如果没有找到任何唯一 SKU，直接返回空数组
        if (empty($uniqueSkus)) {
            return [];
        }

        // 从数据库中查询现有 SKU
        $existingSellerSkus = Db::name('product_seller_sku')
            ->where('spu', $spu)
            ->whereIn('seller_sku', array_keys($uniqueSkus)) // 使用数组键作为条件
            ->column('seller_sku');

        $existingSellerSkus = array_flip($existingSellerSkus); // 转换为键值对以优化查找
        $currentTime = date("Y-m-d H:i:s");

        $resultList = [];

        // 构建最终结果列表
        foreach ($uniqueSkus as $sku => $imageId) {
            if (isset($existingSellerSkus[$sku])) {
                continue; // 跳过已存在的 SKU
            }

            $resultList[] = [
                'spu'          => $spu,
                'seller_sku'   => $sku,
                'image_info'   => $image_info[$imageId] ?? '', // 使用合并的 imageId
                'weight'       => $weight,
                'created_time' => $currentTime,
                'update_time'  => $currentTime,
            ];
        }
        return $resultList;
    }

    /**
     * @desc    获取支持库存
     * @author  luckyXiong
     * @date    2024-12-06
     */
    private function get_inventory_support($inventory_management,$inventory_policy)
    {

          if(!$inventory_management){
               return 3;
          }else{
               if($inventory_policy=='continue'){
                   return 1;
               }else{
                   return 2;
               }
          }
    }


    /**
     * @desc    获取支持库存
     * @author  luckyXiong
     * @date    2024-12-06
     */
    private function get_listing_status($status)
    {    //'产品状态 1:待发布 2:在线 3:已下架 4:已删除 5:发布失败 6:发布中',
         if($status=='active'){
              return 2;
         }elseif($status=='archived'){
             return  3;
         }else{
             return  1;
         }
    }



    //获取入库数据
    private function add_inventory_spu($inventory_product,$seller_sku_product,$product_variant_type){
        htmlLog(['inventory_product'=>$inventory_product,'seller_sku_product'=>$seller_sku_product,'product_variant_type'=>$product_variant_type],OPERATE_LOG . date('Ym') . '/add_inventory_spu/' . date('Ymd') . '.txt');
        $exist_product = Db::name('product')->where(['spu'=>$inventory_product['spu']])->find();
        if(!$exist_product){
            $product_id = Db::name('product')->insertGetId($inventory_product);
        }else{
            $product_id = $exist_product['id']??'';
        }

        //数据维护到仓库sku信息表;
        foreach($seller_sku_product as $k=>$v){
            $seller_sku_product[$k]['product_id'] = $product_id;
        }
        Db::name('product_seller_sku')->insertAll($seller_sku_product);
        return  true;
    }









}